package com.data.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.LineHandler;
import cn.hutool.core.io.file.FileAppender;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.Tailer;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.system.SystemUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.StringUtils;
import com.data.model.Col;
import com.data.model.LogInfo;
import com.data.model.PageVo;
import com.data.model.Test;
import com.data.service.ILogService;
import com.data.service.ITestService;
import com.data.util.result.Result;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * @author helele
 * @date 2021/7/28
 */

@Slf4j
@CrossOrigin
@RestController
@RequestMapping(value = "do")
public class DoController {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private ILogService logService;

    //    @Autowired
//    private MsgProducerService sendService;
//
//    @Autowired
//    private RocketMQTemplate rocketMQTemplate;
//
//
//    @Autowired
//    private RabbitTemplate rabbitTemplate;
    private Pattern pattern = compile("[0-9]*");

    @Autowired
    private ITestService testService;


    /**
     * 每秒限制请求10
     */
    private RateLimiter limiter = RateLimiter.create(10);
//    @Autowired
//    private ConnectionFactory connectionFactory;

    @PostMapping("pro")
    public Result pro(@RequestBody PageVo pageVo) {


        //检查参数是否为空
        boolean passed = checkParamNotNull(pageVo.getIp(), pageVo.getPort(), pageVo.getDatabase(), pageVo.getDriver(), pageVo.getUsername(), pageVo.getPassword(), pageVo.getTableName());
        if (!passed) {
            return Result.paramErr();
        }
        if (pageVo.getMany() == null || pageVo.getMany() < 1) {
            return Result.paramErr();
        }

        if (pageVo.getCols() == null || pageVo.getCols().size() == 0) {
            return Result.paramErr();
        }

        String uuid = UUID.fastUUID().toString();
        LogInfo logInfo = new LogInfo();
        logInfo.setUuid(uuid);
        logInfo.setVo(JSONUtil.toJsonStr(pageVo));
        logInfo.setSuccess(1);
        Connection connection = null;
        try {
            //建立数据库连接
            connection = initDataSource(pageVo).getConnection();
        } catch (SQLException e) {
            logInfo.setRemark(e.getMessage());
            logInfo.setSuccess(0);
            logService.saveOrUpdate(logInfo);
            log.error(e.getMessage());
            return Result.failure("数据库连接异常!请查看后台日志!");
        }
        //执行测试sql
        try {
            String sql = "select 1 from dual;";
            //sql执行是否成功;
            boolean success = connection.prepareStatement(sql).execute();
            if (success) {
                log.info("执行:select 1 from dual;成功!");
            } else {
                log.error("执行select 1 from dual;失败!");
            }
        } catch (SQLException e) {

            try {
                connection.close();
            } catch (SQLException exception) {
                log.error(exception.getMessage());
            }

            //sql执行异常
            log.error(e.getMessage());
            logInfo.setRemark(e.getMessage());
            logInfo.setSuccess(0);
            logService.saveOrUpdate(logInfo);
            return Result.failure("测试sql执行异常");
        }
        //数据库连接无异常，可以正常执行sql，开干
        long createSql = 0;
        long executeSql = 0;
        try {
            TimeInterval timer = DateUtil.timer();
            StringBuilder insertSql = createInsertSql(pageVo);
            createSql = timer.interval();
            log.info("构建sql花费时间(毫秒):" + createSql);

            //存储sql
            String now = DateUtil.now();
            String path = "/Users/helele/work/temp/sql/sqlTemp" + now + ".sql";
            boolean exist = FileUtil.exist(path);
            if (exist) {
                FileUtil.del(path);
            }
            File file = FileUtil.file(path);
            try {

                FileAppender fileAppender = new FileAppender(file, 8, true);
                fileAppender.append(insertSql.toString());
                fileAppender.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }

            TimeInterval timer2 = DateUtil.timer();
            connection.prepareStatement(insertSql.toString()).execute();
            executeSql = timer2.interval();
            log.info("执行sql花费时间(毫秒):" + executeSql);


        } catch (SQLException e) {
            e.printStackTrace();
            log.error("测试插入10000条数据异常!");
            logInfo.setRemark(e.getMessage());
            logInfo.setSuccess(0);
            logService.saveOrUpdate(logInfo);
            return Result.failure();
        } finally {
            try {
                connection.close();
            } catch (SQLException e) {
                logInfo.setRemark(e.getMessage());
                logInfo.setSuccess(0);
                logService.saveOrUpdate(logInfo);
                log.error("关闭sql连接异常!");
                log.error(e.getMessage());
            }
        }
        logInfo.setRemark("构建sql花费时间(毫秒):" + createSql + ";执行sql花费时间(毫秒):" + executeSql + ";");
        logInfo.setSuccess(1);
        logService.saveOrUpdate(logInfo);
        return Result.success("执行成功!流水号:" + uuid);
    }


    private boolean checkParamNotNull(String... param) {
        if (param == null || param.length == 0) {
            return false;
        }
        for (String item : param) {
            if (item == null || StringUtils.isEmpty(item.trim())) {
                return false;
            }
        }
        return true;
    }

    private DataSource initDataSource(PageVo vo) {
        String ip = vo.getIp();
        String port = vo.getPort();
        String database = vo.getDatabase();
        String other = StringUtils.isEmpty(vo.getOtherInfo()) ? "useUnicode=true&characterEncoding=utf8?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true" : vo.getOtherInfo();
        String url = "jdbc:mysql://" + ip + ":" + port + "/" + database + (org.springframework.util.StringUtils.hasText(other) ? "?" + other : "");
        final String username = vo.getUsername();
        final String password = vo.getPassword();
        final String driverClassName = vo.getDriver();
        final Integer initialSize = 2;

        final Integer minIdle = 1;

        final Integer maxActive = 20;

        //最长等待时间
        final Integer maxWait = 60000;

        final Integer timeBetweenEvictionRunsMillis = 60000;

        final Integer minEvictableIdleTimeMillis = 300000;

        final Boolean testWhileIdle = true;

        final Boolean testOnBorrow = false;

        final Boolean testOnReturn = false;

        final Boolean poolPreparedStatements = true;

        final Integer maxPoolPreparedStatementPerConnectionSize = 20;

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        dataSource.setDriverClassName(driverClassName);
        //定义初始连接数
        dataSource.setInitialSize(initialSize);
        //最小空闲
        dataSource.setMinIdle(minIdle);
        //定义最大连接数
        dataSource.setMaxActive(maxActive);
        //最长等待时间
        dataSource.setMaxWait(maxWait);

        // 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);

        // 配置一个连接在池中最小生存的时间，单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        dataSource.setTestWhileIdle(testWhileIdle);
        dataSource.setTestOnBorrow(testOnBorrow);
        dataSource.setTestOnReturn(testOnReturn);

        // 打开PSCache，并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(poolPreparedStatements);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        return dataSource;
    }

    private StringBuilder createInsertSql(PageVo pageVo) {
        StringBuilder sql = new StringBuilder(" insert into  ");
        sql.append(pageVo.getTableName()).append("(");
        //拼接插入的列
        for (int index = 0; index < pageVo.getCols().size(); index++) {
            sql.append("`").append(pageVo.getCols().get(index).getName()).append("`");
            if (index < pageVo.getCols().size() - 1) {
                sql.append(",");
            }
        }
        sql.append(")").append(" values ");

        int x = 1;
        while (x < pageVo.getMany() + 1) {

            sql.append("( ");
            for (int index = 0; index < pageVo.getCols().size(); index++) {
                sql.append("'");
                Col col = pageVo.getCols().get(index);
                //判断是否需要自增
                if (col.isAuto()) {
                    //如果给的值为空且需要自增就输入x
                    if (StringUtils.isEmpty(col.getValue())) {
                        sql.append(x);
                    } else {
                        //判断给的是否是一个数字
                        if (pattern.matcher(col.getValue()).matches()) {
                            //如果数字不超过十位
                            if (col.getValue().trim().length() < 10) {
                                sql.append((Integer.parseInt(col.getValue().trim()) + x));
                            } else {
                                //超过十位但是不超过19位，超过19位parseLong会报错，因为超出Long存储的最大值---坑，暂不处理
                                sql.append((Long.parseLong(col.getValue()) + x));
                            }
                        } else {
                            //判断是否数字结尾
                            if (pattern.matcher(col.getValue().substring(col.getValue().length() - 1)).matches()) {
                                //获取后N位数字
                                Map<String, String> colValue = getLastNumber(col.getValue());
                                String lastNumber = MapUtil.getStr(colValue, "num");
                                String val = MapUtil.getStr(colValue, "val");
                                //不足十位
                                if (lastNumber.length() < 10) {
                                    sql.append(val).append((Integer.parseInt(lastNumber) + x));
                                } else {
                                    //超过十位
                                    sql.append(val).append((Long.parseLong(lastNumber) + x));
                                }
                            } else if (pattern.matcher(col.getValue().substring(0, 1)).matches()) {
                                //以数字开头
                                Map<String, String> map = getFirstNumber(col.getValue());
                                String firstNumber = MapUtil.getStr(map, "num");
                                String otherStr = MapUtil.getStr(map, "val");
                                //不足十位
                                if (firstNumber.length() < 10) {
                                    sql.append((Integer.parseInt(firstNumber) + x)).append(otherStr);
                                } else {
                                    //超过十位
                                    sql.append((Long.parseLong(firstNumber) + x)).append(otherStr);
                                }
                            } else {
                                //既不是以数字结尾也不是以数字开头，无法自增
                                log.error(col.getName() + "字段既不是以数字结尾也不是以数字开头，无法自增!");
                                sql.append(col.getValue());
                            }
                        }
                    }

                } else if (col.isUuid()) {
                    sql.append(IdUtil.objectId());
                } else {
                    sql.append(col.getValue());
                }
                sql.append("'");
                if (index < pageVo.getCols().size() - 1) {
                    sql.append(",");
                }
            }
            sql.append(" ) ");
            if (x < pageVo.getMany()) {
                sql.append(",");
            } else {
                sql.append(";");
            }
            x++;
        }


        return sql;
    }

    /**
     * 取字符串中的后N位数字
     *
     * @param str 需要解析的字符串
     * @return 提取的后N位数字
     */
    private Map<String, String> getLastNumber(String str) {
        Map<String, String> colVal = new HashMap<>();

        StringBuilder num = new StringBuilder();
        StringBuilder val = new StringBuilder();
        boolean isNum = true;
        for (int x = str.length() - 1; x >= 0; x--) {
            String s = String.valueOf(str.charAt(x));
            if (isNum && pattern.matcher(s).matches()) {
                num.append(s);
            } else {
                isNum = false;
                val.append(s);
            }
        }
        colVal.put("num", num.reverse().toString());
        colVal.put("val", val.reverse().toString());
        return colVal;
    }

    /**
     * 取字符串中的前N位数字
     *
     * @param str 需要解析的字符串
     * @return 提取的前N位数字
     */
    private Map<String, String> getFirstNumber(String str) {
        boolean isNumber = true;
        StringBuilder num = new StringBuilder();
        StringBuilder val = new StringBuilder();
        for (int x = 0; x < str.length(); x++) {
            String s = String.valueOf(str.charAt(x));
            if (isNumber && pattern.matcher(s).matches()) {
                num.append(s);
            } else {
                isNumber = false;
                val.append(s);
            }
        }
        Map<String, String> colValue = new HashMap<>();
        colValue.put("num", num.toString());
        colValue.put("val", val.toString());

        return colValue;
    }


    @PostMapping("read")
    public Result readFile() {
        String path = "/Users/helele/work/公司/涉密.xlsx";
        ExcelReader reader = ExcelUtil.getReader(path, 2);
        List<List<Object>> read = reader.read();
        StringBuilder sb = new StringBuilder();
        for (List<Object> line : read) {
//            for (int x = 0; x < line.size(); x++) {
            sb.append("insert into  info_publish_whitelist(soc_code) values ('");
            sb.append(line.get(2)).append("');\n");
//            sb.append(line.get(1)).append("' ").append(line.get(2)).append("' and bank_no ='").append(line.get(0)).append("';\n");

//            }
        }
//        System.out.println(sb.toString());
        return Result.success();
    }

    @PostMapping("download")
    public void download(HttpServletResponse response) {

        //条件查询，不执行分页操作
//        List<CpecOverdueCreditCorrectDto> cpecOverdueCreditCorrectByParam = cpecOverdueCreditCorrectDao.findByParam(vo);
//        final String fileName = "逾期信用信息导出-" + DateUtil.now();
//        final String title = "逾期信用信息";
//        final String sheetName = "逾期信用信息";
//        try {
//            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), CpecOverdueCreditCorrectDto.class, cpecOverdueCreditCorrectByParam);
//            response.setCharacterEncoding("UTF-8");
//            response.setHeader("content-Type", "application/vnd.ms-excel");
//            response.addHeader("Access-Control-Allow-Origin", "*");
//            //response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));//下载文件名不确定
//            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName + ".xlsx", "utf-8"));
//            workbook.write(response.getOutputStream());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }


    @PostMapping("send")
    public Result send() {
//        DefaultMQProducer producer = new
//                DefaultMQProducer("test");
//        try {
//            producer.start();
//        } catch (MQClientException e) {
//            e.printStackTrace();
//        }
//        try {
//            Message message = new Message();
//            message.setTopic("easy");
//            message.setInstanceId(UUID.randomUUID().toString());
//            message.setDelayTimeLevel(0);
//            message.setBody("135".getBytes());
//            message.setTransactionId(UUID.randomUUID().toString());
//            producer.send(message);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
////        sendService.sendMessage();
//        Message m=new Message();
//        m.setTopic("easy");
//        m.setInstanceId(UUID.randomUUID().toString());
//        rocketMQTemplate.send(m);
//        new DefaultMq
//        org.springframework.amqp.rabbit.connection.Connection connection = connectionFactory.createConnection();
//        Channel channel = connection.createChannel(true);
//        try {
//            channel.exchangeDeclare("easyExchange","direct",true);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        rabbitTemplate.getMessageConverter().toMessage()
//        MessageProperties messageProperties = new MessageProperties();
//        messageProperties.setAppId(UUID.fastUUID().toString());
//        rabbitTemplate.send(new Message("a".getBytes(StandardCharsets.UTF_8), messageProperties));
        return Result.success();

    }

    @PostMapping(value = "produceFileData")
    public Result copyFile() {
        File file = FileUtil.file("/Users/helele/work/temp/batch/test20210801.txt");
        FileReader fileReader = new FileReader("/Users/helele/work/temp/batch/test20210801.txt");
//        ArrayList<String> strings = fileReader.readLines(new ArrayList<>());
        FileAppender appender = new FileAppender(file, 16, true);
        TimeInterval timer = DateUtil.timer();
        TimeInterval timer2 = DateUtil.timer();
        int n = 0;
        for (int x = 0; x < 1000000; x++) {
            appender.append(UUID.fastUUID() + "," + UUID.fastUUID() + "," + UUID.fastUUID() + "," + UUID.fastUUID() + ","
                    + UUID.fastUUID() + "," + UUID.fastUUID() + "," + UUID.fastUUID() + "," + UUID.fastUUID() + "," +
                    UUID.fastUUID() + "," + UUID.fastUUID() + "," + UUID.fastUUID() + "," + UUID.fastUUID() + "," +
                    UUID.fastUUID() + "," + UUID.fastUUID() + "," + UUID.fastUUID());
            if (x % 100000 == 0) {
                log.info("写入" + (++n * 100000) + "条数据花费时间:" + timer2.interval());
            }
        }
        log.info("追加一百万条数据花费的时间:" + timer.interval());
        appender.flush();
        return Result.success();
    }

    @PostMapping("readTxt")
    public Result reader() {
//        JvmInfo jvmInfo = new JvmInfo();
//        log.info("JVM信息"+jvmInfo.getInfo());
//        log.info("JVM_Vendor"+jvmInfo.getVendor());
//        log.info("JVM_version"+jvmInfo.getVersion());
//        log.info("JVM_NAMW"+jvmInfo.getName());
        log.info("getFreeMemory" + SystemUtil.getRuntimeInfo().getFreeMemory() / 1024 / 1024);
        log.info("getUsableMemory" + SystemUtil.getRuntimeInfo().getUsableMemory() / 1024 / 1024);
        log.info("getTotalMemory" + SystemUtil.getRuntimeInfo().getTotalMemory() / 1024 / 1024);
        log.info("getMaxMemory" + SystemUtil.getRuntimeInfo().getMaxMemory() / 1024 / 1024);
        File file = FileUtil.file("/Users/helele/work/temp/batch/test20210801.txt");
        List<String> list = FileUtil.readLines(file, StandardCharsets.UTF_8);
        log.info("共计:" + list.size());
        log.info("getFreeMemory" + SystemUtil.getRuntimeInfo().getFreeMemory() / 1024 / 1024);
        log.info("getUsableMemory" + SystemUtil.getRuntimeInfo().getUsableMemory() / 1024 / 1024);
        log.info("getTotalMemory" + SystemUtil.getRuntimeInfo().getTotalMemory() / 1024 / 1024);
        log.info("getMaxMemory" + SystemUtil.getRuntimeInfo().getMaxMemory() / 1024 / 1024);
        return Result.success();
    }


    @PostMapping(value = "saveMultiple")
    public Result saveMultiple() {
        TimeInterval timeInterval = new TimeInterval();
        List<Test> list;
        for (int x = 0; x < 1000; x++) {
            Test test;
            list = new ArrayList<>();
            for (int y = 0; y < 1000; y++) {
                test = new Test();
                test.setCol1(UUID.fastUUID().toString());
                test.setCol2(UUID.fastUUID().toString());
                test.setCol3(UUID.fastUUID().toString());
                test.setCol4(UUID.fastUUID().toString());
                test.setCol5(UUID.fastUUID().toString());
                test.setCol6(UUID.fastUUID().toString());
                test.setCol7(UUID.fastUUID().toString());
                test.setCol8(UUID.fastUUID().toString());
                test.setCol9(UUID.fastUUID().toString());
                test.setCol10(UUID.fastUUID().toString());
                test.setCol11(UUID.fastUUID().toString());
                test.setCol12(UUID.fastUUID().toString());
                list.add(test);
            }
            testService.saveBatch(list);
        }
        log.info("插入一百万条数据耗时(毫秒):" + timeInterval.interval());

//        testService.saveBatch()
        return Result.success();
    }

    @PostMapping(value = "saveMul")
    public Result saveMul() {
        TimeInterval timeInterval = new TimeInterval();
        Test test;
        List<Test> list;
        list = new ArrayList<>();
        for (int y = 0; y < 100000; y++) {
            test = new Test();
            test.setCol1(UUID.fastUUID().toString());
            test.setCol2(UUID.fastUUID().toString());
            test.setCol3(UUID.fastUUID().toString());
            test.setCol4(UUID.fastUUID().toString());
            test.setCol5(UUID.fastUUID().toString());
            test.setCol6(UUID.fastUUID().toString());
            test.setCol7(UUID.fastUUID().toString());
            test.setCol8(UUID.fastUUID().toString());
            test.setCol9(UUID.fastUUID().toString());
            test.setCol10(UUID.fastUUID().toString());
            test.setCol11(UUID.fastUUID().toString());
            test.setCol12(UUID.fastUUID().toString());
            list.add(test);
        }
        testService.saveBatch(list);
        log.info("一次插入10W条花费时间(毫秒):" + timeInterval.interval());
        return Result.success();
    }

    @PostMapping(value = "saveMul2")
    public Result saveMul2() {
        TimeInterval timeInterval = new TimeInterval();
        Test test;
        for (int y = 0; y < 10000; y++) {
            test = new Test();
            test.setCol1(UUID.fastUUID().toString());
            test.setCol2(UUID.fastUUID().toString());
            test.setCol3(UUID.fastUUID().toString());
            test.setCol4(UUID.fastUUID().toString());
            test.setCol5(UUID.fastUUID().toString());
            test.setCol6(UUID.fastUUID().toString());
            test.setCol7(UUID.fastUUID().toString());
            test.setCol8(UUID.fastUUID().toString());
            test.setCol9(UUID.fastUUID().toString());
            test.setCol10(UUID.fastUUID().toString());
            test.setCol11(UUID.fastUUID().toString());
            test.setCol12(UUID.fastUUID().toString());
            testService.save(test);
        }
        log.info("插入10000条数据花费时间(毫秒):" + timeInterval.interval());
        return Result.success();
    }


    @PostMapping("filter")
    public Result filter() {
        boolean b = limiter.tryAcquire(1);
        if (b) {
            log.info("success");
        } else {
            log.info("failed");
        }
        return Result.success();
    }

    private String filepath = "/Users/helele/work/temp/";
    private String filename = "tailor.txt";

    @PostMapping(value = "fileTailer")
    public Result fileTailer() {
//        Tailer tailer = new Tailer(FileUtil.file("/Users/helele/work/temp/tailor.txt"), new ReadHandler());
//        tailer.start(true);
        try {

            //文件监听服务
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Paths.get(filepath).register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
            // 文件读取行数
            AtomicLong lastPointer = new AtomicLong(0L);
            do {
                WatchKey key = null;
                try {
                    key = watchService.take();
                    List<WatchEvent<?>> watchEvents = key.pollEvents();
                    watchEvents.stream().filter(
                            i -> StandardWatchEventKinds.ENTRY_MODIFY == i.kind()
                                    && filename.equals(((Path) i.context()).getFileName().toString())
                    ).forEach(i -> {
                        if (i.count() > 1) {
                            // "重复事件"
                            return;
                        }

                        File configFile = Paths.get(filepath + "/" + i.context()).toFile();
                        StringBuilder str = new StringBuilder();
//                     读取文件
                        lastPointer.set(getFileContent(configFile, lastPointer.get(), str));
                        if (str.length() != 0) {
                            log.info(str.append("\n").toString());
                        }
                    });
                    key.reset();
                } catch (InterruptedException e) {
                    //send Email
                    e.printStackTrace();
                }

            } while (true);


        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.success();

    }



    private static long getFileContent(File configFile, long beginPointer, StringBuilder str) {
        if (beginPointer < 0) {
            beginPointer = 0;
        }
        RandomAccessFile file = null;
        boolean top = true;
        try {
            file = new RandomAccessFile(configFile, "r");
            if (beginPointer > file.length()) {
                return 0;
            }
            file.seek(beginPointer);
            String line;
            while ((line = file.readLine()) != null) {
                if (top) {
                    top = false;
                }
//                else {
//                    str.append("\n");
//                }
                str.append(new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
            }
            return file.getFilePointer();
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        } finally {
            if (file != null) {
                try {
                    file.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class ReadHandler implements LineHandler {
        @Override
        public void handle(String line) {
            log.info(line);
        }
    }


}






















